package network.course6;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpServerChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Netty 服务端
 */
public class NettyServerListenerSimple {
    /**
     * 创建bootstrap
     */
    private static final ServerBootstrap serverBootstrap=new ServerBootstrap();
    /**
     * worker
     */
    private static final EventLoopGroup work=new NioEventLoopGroup();
    /**
     * 端口号
     */
    private  int port =getPort();

    /**
     * 关闭服务器
     * @return
     */
    public void close(){
        System.out.println("关闭服务器....");
        //优雅退出
        work.shutdownGracefully();
    }

    /**
     * 开启及服务器线程
     */
    public void start(){
        serverBootstrap.group(work).channel(NioSctpServerChannel.class).
                option(ChannelOption.SO_BACKLOG,100)
                .handler(new LoggingHandler());
        //设置事件处理
        try {
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new ServerChannelHandlerSimple());
                }
            });
            System.out.println("netty服务器在[" + port + "]端口启动监听");
            ChannelFuture f = serverBootstrap.bind(port);
            f.channel().closeFuture();
        }catch (Exception e){
            System.out.println("[出现异常] 释放资源");

        }finally {
            close();
        }
    }
    private static int getPort() {
        Double port =(Math.random()+1)*10000;
        return  port.intValue();
    }

    public static void main(String[] args) {
        NettyServerListenerSimple nsl=new NettyServerListenerSimple();
        nsl.start();
    }
}
